package vn.edu.saigontech.ncms.web.system;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.w3c.dom.Document;

import vn.edu.saigontech.ncms.model.system.USD;
import vn.edu.saigontech.ncms.service.USDService;
import vn.edu.saigontech.ncms.util.DateUtil;
import vn.edu.saigontech.ncms.util.ExcelUtil;
import vn.edu.saigontech.ncms.web.BaseAction;

@SuppressWarnings("serial")
public class CurrencyAction extends BaseAction {
	
	private int initYear = 2007;
	private String date;
	private Double amount;
	
	/**/
	private Integer month;
	private Integer year;
	
	public String list() {
		this.month = Calendar.getInstance().get(Calendar.MONTH) + 1;
		this.year = Calendar.getInstance().get(Calendar.YEAR);
		REQUEST().setAttribute("usds", USDService.INSTANCE.findByMonth(this.month, this.year));
		return SUCCESS;
	}
	
	public String updateList() {
		REQUEST().setAttribute("usds", USDService.INSTANCE.findByMonth(this.month, this.year));
		return SUCCESS;
	}
	
	public String exportExcel() {
		List<USD> usds = (List<USD>) USDService.INSTANCE.findByMonth(this.month, this.year);
		RESPONSE().setContentType("application/vnd.ms-excel");
		RESPONSE().setHeader("Content-disposition","attachment; filename=\""+ "Currency Report " + this.month + "-" + this.year + ".xls\"");
		try {
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("Currency " + this.month + "-" + this.year);
			
			HSSFFont fontBold18 = ExcelUtil.makeFont(workbook, "Times New Roman", 18, true);
			HSSFFont fontNormal18 = ExcelUtil.makeFont(workbook, "Times New Roman", 18, false);
			HSSFFont fontBold11 = ExcelUtil.makeFont(workbook, "Times New Roman", 11, true);
			HSSFFont fontNormal11 = ExcelUtil.makeFont(workbook, "Times New Roman", 11, false);
			
			HSSFCellStyle styleCenter_B18 = ExcelUtil.makeCellStyle(workbook, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, fontBold18);
			HSSFCellStyle styleCenter_N18 = ExcelUtil.makeCellStyle(workbook, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, fontNormal18);
			HSSFCellStyle styleCenter_B11 = ExcelUtil.makeCellStyle(workbook, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, fontBold11);
			styleCenter_B11.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
			HSSFCellStyle styleRight_N11 = ExcelUtil.makeCellStyle(workbook, HSSFCellStyle.ALIGN_RIGHT, HSSFCellStyle.VERTICAL_CENTER, fontNormal11);
			HSSFCellStyle styleCenter_N11 = ExcelUtil.makeCellStyle(workbook, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, fontNormal11);
			
			HSSFRow row = sheet.createRow(0);
			row.setHeightInPoints(24);
			HSSFCell cell = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
			cell.setCellStyle(styleCenter_B18);
			String name = this.i18n("currency.report");
			cell.setCellValue(new HSSFRichTextString(name));
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
			
			row = sheet.createRow(1);
			row.setHeightInPoints(24);
			cell = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
			cell.setCellStyle(styleCenter_N18);
			name = this.month + "/" + this.year;
			cell.setCellValue(new HSSFRichTextString(name));
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 2));
			
			row = sheet.createRow(3);
			ExcelUtil.makeColumnLabel(workbook, sheet, row, 0, this.i18n("no"), 256*5, styleCenter_B11);
			ExcelUtil.makeColumnLabel(workbook, sheet, row, 1, this.i18n("date"), 256*18, styleCenter_B11);
			ExcelUtil.makeColumnLabel(workbook, sheet, row, 2, "Vietcombank", 256*18, styleCenter_B11);
			
			int rowCount = 4;
			int size = usds.size();
			for(int i = 0; i < size; i++) {
				row = sheet.createRow(rowCount);
				row.setHeightInPoints(20);
				USD usd = usds.get(i);
				
				// Day
				cell = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
				cell.setCellStyle(styleCenter_N11);
				cell.setCellValue(i+1);
				
				cell = row.createCell(1, HSSFCell.CELL_TYPE_STRING);
				cell.setCellStyle(styleCenter_N11);
				cell.setCellValue(new HSSFRichTextString(DateUtil.toString(usd.getDate(), "MM/dd/yyyy")));
				
				cell = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
				cell.setCellStyle(styleRight_N11);
				cell.setCellValue(usd.getAmount());
				
				rowCount++;
			} 
			workbook.write(RESPONSE().getOutputStream());
		} catch (Exception e) {
			// TODO
		}
		this.addLoggingDetail(BaseAction.REPORT, "logging.currency.report", this.month, this.year+"");
		return NONE;
	}
	
	private Double getOnline() throws Exception {
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("http://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx");
		XPathFactory xpfactory = XPathFactory.newInstance();
		XPath path = xpfactory.newXPath();
		String vnd = path.evaluate("/ExrateList/Exrate[@CurrencyCode='USD']/@Sell", doc);
		Double currency = Double.parseDouble(vnd);
		return currency;
	}
	
	public String getLatest() throws Exception {
		Date currentDate = DateUtil.newDate();
		USD usd = USDService.INSTANCE.findByDate(currentDate);
		if (usd == null) {
			usd = new USD();
		}
		Double currency = getOnline();
		usd.setAmount(currency);
		usd.setDate(currentDate);
		usd = USDService.INSTANCE.persist(usd);
		DecimalFormat format = new DecimalFormat("#,##0");
		RESPONSE().getWriter().print(format.format(usd.getAmount())+";");
		RESPONSE().getWriter().print(DateUtil.toString(usd.getDate()));
		RESPONSE().getWriter().flush();

		double newValue = usd.getAmount();
		this.addLoggingDetail(BaseAction.EDIT, "logging.usd.edit", newValue);
		return NONE; 
	}
	
	public String update() throws Exception {
		Date datedate = DateUtil.fromString(this.date, this.i18n("format.date"));
		USD usd = USDService.INSTANCE.findByDate(datedate);
		if(usd != null) {
			if(this.amount != null) {
				usd.setAmount(this.amount);
			}
		}
		else {
			if(this.amount != null) {
				usd = new USD();
				usd.setDate(datedate);
				usd.setAmount(this.amount);
			}
			else {
				return NONE;
			}
		}
		usd = USDService.INSTANCE.persist(usd);
		
		RESPONSE().getWriter().print(String.format("%.0f", usd.getAmount()));
		RESPONSE().getWriter().flush();

		double newValue = usd.getAmount();
		this.addLoggingDetail(BaseAction.EDIT, "logging.usd.edit", newValue);
		return NONE;
	}
	
	public String getOnlineCurrency() throws Exception {
		Double currency = getOnline();
        RESPONSE().getWriter().print(String.format("{0:0,0}", currency));
		RESPONSE().getWriter().flush();
		return NONE;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public Double getAmount() {
		return amount;
	}

	public void setAmount(Double amount) {
		this.amount = amount;
	}
	
	public Integer getMonth() {
		return month;
	}

	public void setMonth(Integer month) {
		this.month = month;
	}

	public Integer getYear() {
		return year;
	}

	public void setYear(Integer year) {
		this.year = year;
	}
	
	public List<Integer> getYearArr() {
		List<Integer> list = new ArrayList<Integer>();
		int currYear = DateUtil.getYear(new Date());
		for (int i = initYear; i <= currYear; i++) {
			list.add(i);
		}
		return list;
	}
}